# -*- coding: utf-8 -*-
# @Time    : 2024/9/25 13:53
# @Author  : Alvin
# @File    : UserInfoHandler.py
# @Des     :
import logging
import traceback

import decimal

from server.handler.DatabaseHandler import DatabaseHandler
from utils import BussinessUtil


class GetUserInfoHandler:

    def __init__(self):
        self.dbHandler = DatabaseHandler()

    def handle_add_user(self, param):
        """
        新增用户
        :param param:
        :return:
        """
        user_name = param.get("userName", None)
        mobile = param.get("mobile", None)
        balance = param.get("balance", 0)
        if not user_name or not mobile:
            raise Exception("用户名和电话不能为空")
        if balance <= 0:
            raise Exception("用户余额不能 <= 0")
        user_info = BussinessUtil.get_user_info_dict(user_name, mobile, balance)
        is_add_sucess = self.dbHandler.add_user(user_info)
        if isinstance(is_add_sucess, bool):
            return is_add_sucess
        else:
            raise Exception(f"添加用户失败：{is_add_sucess}")

    def get_user_info_by_id(self, user_id):
        if not user_id:
            raise Exception("用户id 不能为空")
        user_info = self.dbHandler.get_user_by_id(user_id)
        return user_info

    def add_user_balance(self, param):
        """
        增加用户余额
        :param param:
        :return:
        """
        try:
            userId = param.get("userId", None)
            add_balance = param.get("balance", 0)
            if not userId:
                raise Exception("用户信息参数不能为空")
            if add_balance <= 0:
                raise Exception("需要增加的余额数量不能<=0")
            user_info = self.dbHandler.get_user_by_id(userId)
            if not user_info:
                raise Exception("根据用户参数未能查询到用户信息，请检查userId 参数是否有误")
            new_balance = user_info['balance'] + decimal.Decimal(add_balance)
            self.dbHandler.update_user_balance_by_id(userId, new_balance)
            return True
        except Exception as ex:
            logging.error(f"增加用户余额异常,异常内容：{str(ex)}")
            logging.error("traceback.format_exc():\n%s" % traceback.format_exc())
